package com.zzg.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.zzg.srb.core.entity.dto.ExcelDictDTO;
import com.zzg.srb.core.mapper.DictMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    //数据列表
    private List<ExcelDictDTO> list = new ArrayList<>();

    //每5条记录存储一次
    private static final int BATH_COUNT = 5;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO data, AnalysisContext context) {

        log.info("解析到一条数据：{}", data);
        list.add(data);

        if (list.size() >= BATH_COUNT){
            //数据保存
            saveData();
            list.clear(); //清空
        }
    }

    private void saveData() {
        log.info("{} 条数据被存储到数据库",list.size());
        //调用批量保存方法
        dictMapper.insertBatch(list);
        log.info("{} 条数据被存储到数据库成功！",list.size());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        //存储剩余不足BATH_COUNT的数据
        saveData();
        log.info("所有数据解析完成");
    }
}
